import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/scene_model.dart';
import '../providers/scene_provider.dart';
import '../providers/light_provider.dart';

// 图标工具类
class IconHelper {
  static IconData getIconData(String iconName) {
    // 预定义图标映射
    final Map<String, IconData> iconMap = {
      'home': Icons.home,
      'wb_sunny': Icons.wb_sunny,
      'nightlight': Icons.nightlight,
      'videocam': Icons.videocam,
      'light': Icons.light,
      'add': Icons.add,
      // 添加更多图标映射...
    };

    return iconMap[iconName] ?? Icons.error;
  }
}

class ScenesScreen extends StatelessWidget {
  const ScenesScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('场景'),
      ),
      body: Consumer<SceneProvider>(
        builder: (context, sceneProvider, child) {
          return Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 800),
              child: GridView.builder(
                padding: EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: MediaQuery.of(context).size.height * 0.05,
                ),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: MediaQuery.of(context).size.width > 600 ? 3 : 2,
                  childAspectRatio: 0.85,
                  crossAxisSpacing: 16,
                  mainAxisSpacing: 16,
                ),
                itemCount: sceneProvider.scenes.length + 1, // +1 for add button
                itemBuilder: (context, index) {
                  if (index == sceneProvider.scenes.length) {
                    return _buildAddSceneCard(context);
                  }
                  return _buildSceneCard(
                    context,
                    sceneProvider.scenes[index],
                    sceneProvider.currentScene?.id == sceneProvider.scenes[index].id,
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSceneCard(BuildContext context, LightScene scene, bool isSelected) {
    return Card(
      elevation: 2,
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: isSelected
            ? BorderSide(
          color: Theme.of(context).colorScheme.primary,
          width: 2,
        )
            : BorderSide.none,
      ),
      child: InkWell(
        onTap: () {
          final sceneProvider = context.read<SceneProvider>();
          final lightProvider = context.read<LightProvider>();

          sceneProvider.selectScene(scene.id);
          lightProvider
            ..setBrightness(scene.brightness)
            ..setColorTemperature(scene.colorTemperature);
        },
        onLongPress: scene.isCustom
            ? () => _showDeleteDialog(context, scene)
            : null,
        child: Stack(
          children: [
            if (isSelected)
              Positioned(
                right: 8,
                top: 8,
                child: Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.check,
                    size: 16,
                    color: Theme.of(context).colorScheme.onPrimary,
                  ),
                ),
              ),
            Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.2),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        IconHelper.getIconData(scene.iconName),
                        size: 48,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      scene.name,
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 8),
                    Text(
                      scene.description,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Theme.of(context).textTheme.bodySmall?.color?.withOpacity(0.8),
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAddSceneCard(BuildContext context) {
    return Card(
      elevation: 2,
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: InkWell(
        onTap: () => _showAddSceneDialog(context),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.2),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.add,
                    size: 48,
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ),
                const SizedBox(height: 16),
                Text(
                  '添加场景',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _showDeleteDialog(BuildContext context, LightScene scene) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除场景'),
        content: Text('确定要删除场景"${scene.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      if (!context.mounted) return;
      context.read<SceneProvider>().deleteScene(scene.id);
    }
  }

  Future<void> _showAddSceneDialog(BuildContext context) async {
    final lightProvider = context.read<LightProvider>();
    final currentBrightness = lightProvider.brightness;
    final currentColorTemp = lightProvider.colorTemperature;

    final result = await showDialog<Map<String, String>>(
      context: context,
      builder: (context) => _AddSceneDialog(
        initialBrightness: currentBrightness,
        initialColorTemp: currentColorTemp,
      ),
    );

    if (result != null) {
      if (!context.mounted) return;
      final newScene = LightScene(
        id: '',  // Will be set by provider
        name: result['name']!,
        description: result['description']!,
        iconName: result['iconName']!,
        brightness: currentBrightness,
        colorTemperature: currentColorTemp,
      );

      context.read<SceneProvider>().addCustomScene(newScene);
    }
  }
}

class _AddSceneDialog extends StatefulWidget {
  final double initialBrightness;
  final double initialColorTemp;

  const _AddSceneDialog({
    required this.initialBrightness,
    required this.initialColorTemp,
  });

  @override
  State<_AddSceneDialog> createState() => _AddSceneDialogState();
}

class _AddSceneDialogState extends State<_AddSceneDialog> {
  final _nameController = TextEditingController();
  final _descriptionController = TextEditingController();
  String _selectedIcon = 'lightbulb';

  final _icons = [
    'lightbulb',
    'wb_sunny',
    'nightlight',
    'highlight',
    'emoji_objects',
    'light_mode',
  ];

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加自定义场景'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(
                labelText: '场景名称',
                hintText: '输入场景名称',
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _descriptionController,
              decoration: const InputDecoration(
                labelText: '场景描述',
                hintText: '输入场景描述',
              ),
              maxLines: 2,
            ),
            const SizedBox(height: 16),
            const Text('选择图标'),
            Wrap(
              spacing: 8,
              children: _icons.map((iconName) {
                return IconButton(
                  icon: Icon(
                    IconHelper.getIconData(iconName),
                  ),
                  color: _selectedIcon == iconName
                      ? Theme.of(context).colorScheme.primary
                      : null,
                  onPressed: () {
                    setState(() {
                      _selectedIcon = iconName;
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () {
            if (_nameController.text.isEmpty) {
              return;
            }
            Navigator.pop(context, {
              'name': _nameController.text,
              'description': _descriptionController.text,
              'iconName': _selectedIcon,
            });
          },
          child: const Text('保存'),
        ),
      ],
    );
  }
}
